package cn.ug.pay.web.controller;

import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.GoldBeanRemarkEnum;
import cn.ug.enums.OrderNOPrefixEnum;
import cn.ug.feign.OrderService;
import cn.ug.mall.bean.OrderBean;
import cn.ug.pay.bean.DueinGoldBeanBean;
import cn.ug.pay.bean.GoldBeanChangeBean;
import cn.ug.pay.bean.GoldBeanEverydayRecordBean;
import cn.ug.pay.mapper.entity.PayGoldBeanRecord;
import cn.ug.pay.service.BankCardService;
import cn.ug.pay.service.PayGoldBeanRecordService;
import cn.ug.pay.service.PayTbillLeasebackService;
import cn.ug.pay.service.PayTbillService;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.SerialNumberWorker;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.gexin.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.ug.util.ConstantUtil.NATIVE_PRI_KEY;

@RestController
@RequestMapping("bean")
public class PayGoldBeanRecordController extends BaseController {
    @Autowired
    private PayGoldBeanRecordService payGoldBeanRecordService;
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private PayTbillService payTbillService;
    @Autowired
    private PayTbillLeasebackService payTbillLeasebackService;
    @Autowired
    private OrderService orderService;

    @PostMapping(value = "/present")
    public SerializeObject presentBeans(String memberId, int beans, int type, String remark, String sign) {
        if (StringUtils.isBlank(memberId) || beans < 1 || StringUtils.isBlank(remark) || StringUtils.isBlank(sign)) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000002");
        }
        String strSign = DigestUtils.md5Hex(beans+memberId+remark+type+NATIVE_PRI_KEY);
        if (!StringUtils.equals(strSign, sign)) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000002");
        }
        PayGoldBeanRecord beanRecord = new PayGoldBeanRecord();
        beanRecord.setOrderNO(OrderNOPrefixEnum.GB.name() + SerialNumberWorker.getInstance().nextId());
        beanRecord.setType(type);
        beanRecord.setRemark(remark);
        beanRecord.setGoldBean(beans);
        beanRecord.setGoldGram(new BigDecimal(beans/10000.0));
        beanRecord.setMemberId(memberId);
        beanRecord.setAddTime(UF.getFormatDateTime(LocalDateTime.now()));
        beanRecord.setSuccessTime(UF.getFormatDateTime(LocalDateTime.now()));
        if (payGoldBeanRecordService.save(beanRecord)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObjectError("00000005");
        }
    }

    @GetMapping(value = "/member/task/status")
    public SerializeObject getMemberTask(@RequestHeader String accessToken) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        //认证绑卡
        int num = bankCardService.validateBindBankCard(loginBean.getId());
        List<JSONObject> result = new ArrayList<JSONObject>();
        if (num > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.BINDING_CARD_REWARDS.getRemark());
            jsonObject.put("result", 1);
            result.add(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.BINDING_CARD_REWARDS.getRemark());
            jsonObject.put("result", 0);
            result.add(jsonObject);
        }
        //购买提单
        num = payTbillService.countSuccessfulNum(loginBean.getId());
        if (num > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.PAY_GOLD_REWARDS.getRemark());
            jsonObject.put("result", 1);
            result.add(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.PAY_GOLD_REWARDS.getRemark());
            jsonObject.put("result", 0);
            result.add(jsonObject);
        }
        //购买体验金
        num = payTbillService.countExperienceSuccessfulNum(loginBean.getId());
        if (num > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.PAY_EXPERIENCE_REWARDS.getRemark());
            jsonObject.put("result", 1);
            result.add(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.PAY_EXPERIENCE_REWARDS.getRemark());
            jsonObject.put("result", 0);
            result.add(jsonObject);
        }
        //回租订单
        num = payTbillLeasebackService.countSuccessfulNum(loginBean.getId());
        if (num > 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.LEASEBACK_SUCCESS_REWARDS.getRemark());
            jsonObject.put("result", 1);
            result.add(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.LEASEBACK_SUCCESS_REWARDS.getRemark());
            jsonObject.put("result", 0);
            result.add(jsonObject);
        }
        //购买金饰
        SerializeObject order = orderService.getSuccessfulNum(loginBean.getId());
        if (order != null && order.getData() != null) {
            num = Integer.parseInt(String.valueOf(order.getData()));
            if (num > 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("task", GoldBeanRemarkEnum.PAY_ORNAMENT_REWARDS.getRemark());
                jsonObject.put("result", 1);
                result.add(jsonObject);
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("task", GoldBeanRemarkEnum.PAY_ORNAMENT_REWARDS.getRemark());
                jsonObject.put("result", 0);
                result.add(jsonObject);
            }
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("task", GoldBeanRemarkEnum.PAY_ORNAMENT_REWARDS.getRemark());
            jsonObject.put("result", 0);
            result.add(jsonObject);
        }
        return new SerializeObject<>(ResultType.NORMAL, result);
    }

    @GetMapping(value = "/member/records")
    public SerializeObject<DataTable<PayGoldBeanRecord>> getMemberBeanRecords(@RequestHeader String accessToken, Integer type, Page page) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        type = type == null ? 0 : type;
        int total = payGoldBeanRecordService.count(loginBean.getId(), type, "");
        page.setTotal(total);
        if (total > 0) {
            List<PayGoldBeanRecord> list = payGoldBeanRecordService.query(loginBean.getId(), type, "", "", "", PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayGoldBeanRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayGoldBeanRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<PayGoldBeanRecord>()));
    }

    @GetMapping(value = "/records")
    public SerializeObject<DataTable<PayGoldBeanRecord>> getRecords(String memberId, Integer type, String remark, Page page, Order order) {
        memberId = UF.toString(memberId);
        remark = UF.toString(remark);
        type = type == null ? 0 : type;
        int total = payGoldBeanRecordService.count(memberId, type, remark);
        page.setTotal(total);
        if (total > 0) {
            List<PayGoldBeanRecord> list = payGoldBeanRecordService.query(memberId, type, remark, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayGoldBeanRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayGoldBeanRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<PayGoldBeanRecord>()));
    }

    @GetMapping(value = "/records/export")
    public void exportData(HttpServletResponse response, String memberId, Integer type, Integer menu, String remark, Order order) {
        memberId = UF.toString(memberId);
        remark = UF.toString(remark);
        type = type == null ? 0 : type;
        menu = menu == null ? 0 : menu;
        List<PayGoldBeanRecord> list = payGoldBeanRecordService.query(memberId, type, remark, order.getOrder(), order.getSort(), 0, 0);
        if(list != null && !list.isEmpty()){
            int index = 1;
            for (PayGoldBeanRecord bean : list) {
                bean.setIndex(index);
                index++;
            }
            if (menu == 0) {
                for (PayGoldBeanRecord bean : list) {
                    if (bean.getType() == 1) {
                        bean.setTypeMark("收入");
                    } else if (bean.getType() == 2) {
                        bean.setTypeMark("支出");
                    }
                }
                String[] columnNames = { "序号", "流水号", "收支类型", "收支说明", "金豆个数（个）", "预估黄金（克）", "操作时间"};
                String [] columns = {"index",  "orderNO", "typeMark", "remark", "goldBean", "goldGram", "addTime"};
                String fileName = "金豆账户详表";
                ExportExcelController<PayGoldBeanRecord> export = new ExportExcelController<PayGoldBeanRecord>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            } else if (menu == 1) {
                String[] columnNames = { "序号", "流水号","收入说明", "收入金豆（个）", "预估获得黄金（克）", "金豆到账时间"};
                String [] columns = {"index",  "orderNO", "remark", "goldBean", "goldGram", "successTime"};
                String fileName = "金豆收入详表";
                ExportExcelController<PayGoldBeanRecord> export = new ExportExcelController<PayGoldBeanRecord>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            } else if (menu == 2) {
                String[] columnNames = { "序号", "流水号","支出说明", "支出金豆（个）", "预估可兑黄金（克）", "金豆支出时间"};
                String [] columns = {"index",  "orderNO", "remark", "goldBean", "goldGram", "successTime"};
                String fileName = "金豆支出详表";
                ExportExcelController<PayGoldBeanRecord> export = new ExportExcelController<PayGoldBeanRecord>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            }
        }
    }

    @GetMapping(value = "/member/statistics")
    public SerializeObject<GoldBeanChangeBean> getMemberBeanStatistics(@RequestHeader String accessToken) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        GoldBeanChangeBean beanChangeBean = payGoldBeanRecordService.queryForBeanByMemberId(loginBean.getId());
        if (beanChangeBean != null) {
            beanChangeBean.setUsableGram(new BigDecimal(beanChangeBean.getUsableBean()/10000.0));
        }
        return new SerializeObject<>(ResultType.NORMAL, beanChangeBean);
    }

    @GetMapping(value = "/change/list")
    public SerializeObject<DataTable<GoldBeanChangeBean>> queryForList(@RequestHeader String accessToken, Order order, Page page, Integer type, String name, String mobile, Integer beanFrom, Integer beanTo, String startDate, String endDate) {
        name = UF.toString(name);
        mobile = UF.toString(mobile);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        beanFrom = beanFrom == null ? -1 : beanFrom;
        beanTo = beanTo == null ? -1 : beanTo;
        type = type == null ? 0 : type;
        int total = payGoldBeanRecordService.countForBean(type, name, mobile, beanFrom, beanTo, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<GoldBeanChangeBean> list = payGoldBeanRecordService.queryForBean(type, name, mobile, beanFrom, beanTo, startDate, endDate, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            if (list != null && list.size() > 0) {
                for (GoldBeanChangeBean bean : list) {
                    if (StringUtils.isNotBlank(bean.getMobile())) {
                        bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                    }
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldBeanChangeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldBeanChangeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GoldBeanChangeBean>()));
    }

    @GetMapping(value = "/change/export")
    public void exportData(HttpServletResponse response, Order order, Integer type, String name, String mobile, Integer beanFrom, Integer beanTo, String startDate, String endDate) {
        name = UF.toString(name);
        mobile = UF.toString(mobile);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        beanFrom = beanFrom == null ? -1 : beanFrom;
        beanTo = beanTo == null ? -1 : beanTo;
        type = type == null ? 0 : type;
        List<GoldBeanChangeBean> list = payGoldBeanRecordService.queryForBean(type, name, mobile, beanFrom, beanTo, startDate, endDate, order.getOrder(), order.getSort(), 0, 0);
        if(list != null && !list.isEmpty()){
            int index = 1;
            for (GoldBeanChangeBean bean : list) {
                if (StringUtils.isNotBlank(bean.getMobile())) {
                    bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                }
                bean.setIndex(index);
                index++;
            }
            if (type == 0) {
                String[] columnNames = { "序号", "手机号","用户姓名", "收入金豆总数（个）", "支出金豆总数（个）", "可用金豆（个）", "账户创建时间"};
                String [] columns = {"index",  "mobile", "name", "incomeBean", "outgoBean", "usableBean", "addTime"};
                String fileName = "金豆变动总表";
                ExportExcelController<GoldBeanChangeBean> export = new ExportExcelController<GoldBeanChangeBean>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            } else if (type == 1) {
                String[] columnNames = { "序号", "手机号","用户姓名", "收入金豆（个）", "预估获得黄金（克）"};
                String [] columns = {"index",  "mobile", "name", "incomeBean", "incomeGram"};
                String fileName = "金豆收入表";
                ExportExcelController<GoldBeanChangeBean> export = new ExportExcelController<GoldBeanChangeBean>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            } else if (type == 2) {
                String[] columnNames = { "序号", "手机号","用户姓名", "支出金豆（个）", "预估可兑黄金（克）"};
                String [] columns = {"index",  "mobile", "name", "outgoBean", "outgoGram"};
                String fileName = "金豆支出表";
                ExportExcelController<GoldBeanChangeBean> export = new ExportExcelController<GoldBeanChangeBean>();
                export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
            }
        }
    }

    @GetMapping(value = "/everyday/records")
    public SerializeObject<DataTable<GoldBeanEverydayRecordBean>> getRecords(String memberId, Page page, Order order) {
        memberId = UF.toString(memberId);
        int total = payGoldBeanRecordService.countForEveryRecord(memberId);
        page.setTotal(total);
        if (total > 0) {
            List<GoldBeanEverydayRecordBean> list = payGoldBeanRecordService.queryForEveryRecord(memberId, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldBeanEverydayRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldBeanEverydayRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GoldBeanEverydayRecordBean>()));
    }

    @GetMapping(value = "/everyday/records/export")
    public void exportData(HttpServletResponse response, String memberId, Order order) {
        memberId = UF.toString(memberId);
        List<GoldBeanEverydayRecordBean> list = payGoldBeanRecordService.queryForEveryRecord(memberId, order.getOrder(), order.getSort(), 0, 0);
        if(list != null && !list.isEmpty()){
            int index = 1;
            for (GoldBeanEverydayRecordBean bean : list) {
                bean.setIndex(index);
                index++;
            }
            String[] columnNames = { "序号", "当日收入金豆（个）", "当日支出金豆（个）", "当日日期"};
            String [] columns = {"index",  "incomeBean", "outgoBean", "tradeDate"};
            String fileName = "金豆变动详表";
            ExportExcelController<GoldBeanEverydayRecordBean> export = new ExportExcelController<GoldBeanEverydayRecordBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/duein/list")
    public SerializeObject<DataTable<DueinGoldBeanBean>> getRecords(String memberId, Page page) {
        memberId = UF.toString(memberId);
        int total = payGoldBeanRecordService.countForDueinBean(memberId);
        page.setTotal(total);
        if (total > 0) {
            List<DueinGoldBeanBean> list = payGoldBeanRecordService.queryForDueinBean(memberId, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<DueinGoldBeanBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<DueinGoldBeanBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<DueinGoldBeanBean>()));
    }

    @GetMapping(value = "/duein/export")
    public void exportData(HttpServletResponse response, String memberId) {
        memberId = UF.toString(memberId);
        List<DueinGoldBeanBean> list = payGoldBeanRecordService.queryForDueinBean(memberId, 0, 0);
        if(list != null && !list.isEmpty()){
            int index = 1;
            for (DueinGoldBeanBean bean : list) {
                bean.setIndex(index);
                index++;
            }
            String[] columnNames = { "序号", "流水号", "关联产品名称", "回租周期", "年化收益%", "待收—回租奖励（元）", "待收—奖励金豆（个）", "待收—奖励金豆（个）", "回租到期时间"};
            String [] columns = {"index",  "orderNO", "productName", "leasebackDays", "yearIncome", "incomeAmount", "incomeBeans", "incomeGram", "endTime"};
            String fileName = "待收金豆详表";
            ExportExcelController<DueinGoldBeanBean> export = new ExportExcelController<DueinGoldBeanBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }
}





